
import Foundation

// MARK: - Codable 数组扩展
extension Array where Element: Codable {
    
    /// 对象数组转 JSON 字符串
    func toJSONString(prettyPrinted: Bool = false) -> String? {
        let encoder = JSONEncoder()
        if prettyPrinted {
            encoder.outputFormatting = .prettyPrinted
        }
        do {
            let data = try encoder.encode(self)
            return String(data: data, encoding: .utf8)
        } catch {
            print("编码失败: \(error)")
            return nil
        }
    }
    
    // let models = [TestModel].fromJSONString(anyValue)
    
    /// JSON 字符串转对象数组
    static func fromJSONString(_ jsonString: String) -> [Element]? {
        guard let data = jsonString.data(using: .utf8) else { return nil }
        let decoder = JSONDecoder()
        do {
            return try decoder.decode([Element].self, from: data)
        } catch {
            print("解码失败: \(error)")
            return nil
        }
    }
    
    /// 对象数组转字典数组
    func toDictionaryArray() -> [[String: Any]]? {
        do {
            let data = try JSONEncoder().encode(self)
            return try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]]
        } catch {
            print("转字典失败: \(error)")
            return nil
        }
    }
    
    /// 字典数组转对象数组
    static func fromDictionaryArray(_ array: [[String: Any]]) -> [Element]? {
        do {
            let data = try JSONSerialization.data(withJSONObject: array, options: [])
            return try JSONDecoder().decode([Element].self, from: data)
        } catch {
            print("从字典解码失败: \(error)")
            return nil
        }
    }
}


extension Encodable {
    /// 当前对象转 JSON 字符串
    func toJSONString(prettyPrinted: Bool = false) -> String? {
        let encoder = JSONEncoder()
        if prettyPrinted {
            encoder.outputFormatting = .prettyPrinted
        }
        do {
            let data = try encoder.encode(self)
            return String(data: data, encoding: .utf8)
        } catch {
            print("编码失败: \(error)")
            return nil
        }
    }
    
    /// 当前对象转字典 [String: Any]
    func toDictionary() -> [String: Any]? {
        do {
            let data = try JSONEncoder().encode(self)
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print("转字典失败: \(error)")
            return nil
        }
    }
}

extension Decodable {
    /// 从 JSON 字符串初始化对象
    static func fromJSONString(_ jsonString: String) -> Self? {
        guard let data = jsonString.data(using: .utf8) else { return nil }
        let decoder = JSONDecoder()
        do {
            return try decoder.decode(Self.self, from: data)
        } catch {
            print("解码失败: \(error)")
            return nil
        }
    }
    
    /// 从字典 [String: Any] 初始化对象
    static func fromDictionary(_ dict: [String: Any]) -> Self? {
        do {
            let data = try JSONSerialization.data(withJSONObject: dict, options: [])
            return try JSONDecoder().decode(Self.self, from: data)
        } catch {
            print("从字典解码失败: \(error)")
            return nil
        }
    }
}
